package com.woniuxy.health.manager.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.health.manager.dto.PermissionDto;
import com.woniuxy.health.manager.mapper.ManagerRoleMapper;
import com.woniuxy.health.manager.mapper.PerssionMapper;
import com.woniuxy.health.manager.mapper.RolePermissionMapper;
import com.woniuxy.health.model.manager.ManagerRole;
import com.woniuxy.health.model.manager.Perssion;
import com.woniuxy.health.manager.service.IPerssionService;
import com.woniuxy.health.model.manager.RolePermission;
import com.woniuxy.health.manager.vo.PageVo;
import com.woniuxy.health.manager.vo.PermissionMenuVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author woniuxy
 * @since 2023-09-04
 */
@Service
public class PerssionServiceImpl extends ServiceImpl<PerssionMapper, Perssion> implements IPerssionService {

    private final PerssionMapper perssionMapper;
    private final RolePermissionMapper rolePermissionMapper;
    private final ManagerRoleMapper managerRoleMapper;

    @Autowired
    public PerssionServiceImpl(PerssionMapper perssionMapper, RolePermissionMapper rolePermissionMapper, ManagerRoleMapper managerRoleMapper) {
        this.perssionMapper = perssionMapper;
        this.rolePermissionMapper = rolePermissionMapper;
        this.managerRoleMapper = managerRoleMapper;
    }

    @Override
    public List<PermissionMenuVo> findPermission() {

        List<Perssion> menus = perssionMapper.selectList(null);
        //先过滤一级菜单
        List<PermissionMenuVo> list = menus.stream().filter(e -> e.getParentId() == -1).map(e -> {
            PermissionMenuVo pmv = new PermissionMenuVo();
            pmv.setId(e.getId());
            pmv.setPerssionName(e.getPerssionName());
            //通过一级菜单，过滤找到对应的二级
            List<PermissionMenuVo> collect = menus.stream().filter(m -> m.getParentId() == e.getId()).map(m -> {
                PermissionMenuVo spmv = new PermissionMenuVo();
                spmv.setId(m.getId());
                spmv.setPerssionName(m.getPerssionName());
                spmv.setUrl(m.getUrl());
                return spmv;
            }).collect(Collectors.toList());
            //将采集的二级菜单，存储到一级菜单中
            pmv.setChildren(collect);
            return pmv;
        }).collect(Collectors.toList());
        return list;
    }

    @Override
    public List<PermissionMenuVo> findRolePermission(Long managedId) {
        // 根据管理员ID查询管理员角色对象
        ManagerRole managerRole = managerRoleMapper.selectOne(Wrappers.lambdaQuery(ManagerRole.class)
                .eq(ManagerRole::getManagerId, managedId));
        //根据角色ID查找对应的权限
        List<RolePermission> rolePermissions = rolePermissionMapper.selectList(Wrappers.lambdaQuery(RolePermission.class)
                .eq(RolePermission::getRoleId, managerRole.getRoleId()));
        List<Long> collect1 = rolePermissions.stream().map(RolePermission::getPerssionId).collect(Collectors.toList());
        List<Perssion> menus = perssionMapper.selectList(Wrappers.lambdaQuery(Perssion.class)
                .in(Perssion::getId, collect1));
        //先过滤一级菜单
        List<PermissionMenuVo> list = menus.stream().filter(e -> e.getParentId() == -1).map(e -> {
            PermissionMenuVo pmv = new PermissionMenuVo();
            pmv.setId(e.getId());
            pmv.setPerssionName(e.getPerssionName());
            //通过一级菜单，过滤找到对应的二级
            List<PermissionMenuVo> collect = menus.stream().filter(m -> m.getParentId() == e.getId()).map(m -> {
                PermissionMenuVo spmv = new PermissionMenuVo();
                spmv.setId(m.getId());
                spmv.setPerssionName(m.getPerssionName());
                spmv.setUrl(m.getUrl());
                return spmv;
            }).collect(Collectors.toList());
            //将采集的二级菜单，存储到一级菜单中
            pmv.setChildren(collect);
            return pmv;
        }).collect(Collectors.toList());
        return list;
    }

    @Override
    public PageVo listAll(Page<Perssion> page, PermissionDto permissionDto) {
        Page<Perssion> p = perssionMapper.selectPage(page, Wrappers.lambdaQuery(Perssion.class)
                .likeRight(StringUtils.hasLength(permissionDto.getPerssionName()), Perssion::getPerssionName, permissionDto.getPerssionName())
                .eq(permissionDto.getUrlType() != null, Perssion::getUrlType, permissionDto.getUrlType())
                .eq(permissionDto.getParentId() != null, Perssion::getParentId, permissionDto.getParentId())
                .ge(permissionDto.getStartDateTime() != null, Perssion::getCreateTime, permissionDto.getStartDateTime())
                .lt(permissionDto.getEndDateTime() != null, Perssion::getCreateTime, permissionDto.getEndDateTime()));
        return new PageVo(p.getTotal(), p.getRecords());
    }

    @Override
    public void deletePermission(Long id) {
        //如果删除的是一级菜单，还要删除二级子菜单
        Perssion permission = perssionMapper.selectById(id);
        if (permission.getParentId() == -1) {//它是一级菜单
            //查询二级菜单
            List<Perssion> permissions = perssionMapper
                    .selectList(Wrappers.lambdaQuery(Perssion.class)
                            .eq(Perssion::getParentId, id));
            //删除二级菜单对应的绑定关系，以及删除所有的二级
            permissions.forEach(e -> {
                rolePermissionMapper
                        .delete(Wrappers.lambdaQuery(RolePermission.class)
                                .eq(RolePermission::getPerssionId, e.getId()));
                perssionMapper.deleteById(e.getId());
            });
        }
        //删除自己的关系
        rolePermissionMapper
                .delete(Wrappers.lambdaQuery(RolePermission.class)
                        .eq(RolePermission::getPerssionId, id));
        //删除自己
        perssionMapper.deleteById(id);
    }

    private List<PermissionMenuVo> getPermissionMenuVos(List<Perssion> permissions) {
        //先过滤一级菜单
        List<Perssion> finalPermissions = permissions;
        List<PermissionMenuVo> datas = permissions.stream().filter(e -> e.getParentId() == -1).map(e -> {
            PermissionMenuVo pmv = new PermissionMenuVo();
            pmv.setId(e.getId());
            pmv.setPerssionName(e.getPerssionName());
            //再过滤一次找到二级菜单，并放置到一级菜单中去
            List<PermissionMenuVo> children = finalPermissions.stream().filter(m -> m.getParentId() == e.getId()).map(m -> {
                PermissionMenuVo pmvc = new PermissionMenuVo();
                pmvc.setId(m.getId());
                pmvc.setPerssionName(m.getPerssionName());
                pmvc.setUrl(m.getUrl());
                return pmvc;
            }).collect(Collectors.toList());
            pmv.setChildren(children);
            return pmv;
        }).collect(Collectors.toList());
        return datas;
    }

    @Override
    public List<PermissionMenuVo> findAll() {
        List<Perssion> permissions = perssionMapper.selectList(null);
        return getPermissionMenuVos(permissions);//将集合的数据，转换的树形数据
    }

    @Override
    public Perssion findPermissionByName(String permissionName) {
        Perssion perssion = perssionMapper.selectOne(Wrappers.lambdaQuery(Perssion.class)
                .eq(Perssion::getPerssionName, permissionName));
        return perssion;
    }
}
